package com.e3.web.login.server;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.e3.basdoc.corp.model.CorpModel;
import com.e3.basdoc.corp.server.CorpServiceClient;
import com.e3.core.base.Session;
import com.e3.core.base.SessionContext;
import com.e3.sysmg.security.model.UserModel;
import com.e3.sysmg.security.server.SecurityServiceClient;
import com.e3.web.core.server.HttpSessionHelper;
/**
 * 该类封装登录过程的所有过程。
 * 
 * @author Janty
 *
 */
public final class LoginHelper {
	
	private static Map<String,Session> loginedUsers = new Hashtable<String,Session>();
	
	private LoginHelper(){
		
	}
	/**
	 * 获取当前用户的Session对象。如果没有则创建新对象。
	 * 当执行RPC调用时在<ul>com.e3.web.core.server.GWTServiceServlet</ul>
	 * 的before方法中将Session放入SessionContext供服务器端使用。
	 * @param request
	 * @return
	 */
	public static Session getSession(HttpServletRequest request){
		Session session = (Session)HttpSessionHelper.getAttribute(request, Session.GLOBAL_NAME);
		if(session == null){
			session = SessionContext.getSession();
			HttpSessionHelper.setAttribute(request, Session.GLOBAL_NAME, session);
		}
		if(SessionContext.isDeveloping()){
			loginedUsers.put(getSessionKey(session), session);
		}
		return session;
	}

	/**
	 * 记录当前登录用户
	 * 转发请求到主界面
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public static void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		putUserSession(getSession(request));
		RequestDispatcher rd = request.getRequestDispatcher("/Index.jsp");
		rd.forward(request, response);
	}
	/**
	 * 注销到登录界面。同时清除用户信息。
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public static void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		gotoLogin(request, response);
	}
	/**
	 * 跳转到登陆页面，同时清除用户信息。
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public static void gotoLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		removeUserSession(request,getSession(request));
		String uri = request.getRequestURI();
		String base = "";
		int index = uri.indexOf("/", 1);
		if(index>0){
			base = uri.substring(0,index);
		}
		java.io.PrintWriter out = response.getWriter();   
		out.println("<html>");
		out.println(base);
		out.println("<script>"); 
		String wndUrl = base+"/Login.jsp";
		String wnd = "window.top.location.href='"+wndUrl+"'";
		out.println(wnd);   
		out.println("</script>");   
		out.println("</html>"); 
	}
	/**
	 * 获取Session对象在loginedUsers Map中的key值。
	 * @param request
	 * @return
	 */
	public static String getSessionKey(Session session){
		String userCode = session.getUserCode();
		String corpCode = session.getCorpCode();
		return getMapKey(userCode, corpCode);
	}
	/**
	 * 
	 * @param userCode
	 * @param corpCode
	 * @return
	 */
	private static String getMapKey(String userCode,String corpCode){
		return corpCode+"#"+userCode;
	}
	/**
	 * 判断用户是否已经登录。一个用户只能在一个地方登录一次，
	 * 不能同时在多个地方登录。
	 * @param request
	 * @return
	 */
	public static boolean isLogined(HttpServletRequest request){
		Session session = getSession(request);
		String key = getSessionKey(session);
		Session ses = (Session)loginedUsers.get(key);
		
		if(ses == null){
			return false;
		}
		if(ses.getLoginAddress().equals(session.getLoginAddress())){
			return true;
		}
		return false;
	}
	/**
	 * 记录当前登录用户
	 * @param request
	 */
	private static void putUserSession(Session session){
		enhanceSession(session);
		String key = getSessionKey(session);
		loginedUsers.put(key, session);
	}
	
	private static void enhanceSession(Session session){
		if(session.getCorpID()==null){
			CorpModel corp = CorpServiceClient.getCorpQueryService().getSimpleCorpByCode(session.getCorpCode());
			if(corp!=null){
				session.setCorpID(corp.getId());
				session.setCorpName(corp.getName());
			}
			else{
				session.setCorpID(0L);
			}
		}
		
		if(session.getUserID()==null){
			UserModel user = SecurityServiceClient.getSecQueryService().getUserByCode(session.getUserCode());
			if(user!=null){
				session.setUserID(user.getId());
				session.setUserName(user.getName());
			}
			else{
				session.setUserID(0L);
			}
		}

	}
	
	/**
	 * 删除当前登录用户
	 * @param request
	 */
	private static void removeUserSession(HttpServletRequest request,Session session){
		String key = getSessionKey(session);
		loginedUsers.remove(key);
		HttpSessionHelper.removeAttribute(request, Session.GLOBAL_NAME);
	}
	
	
}
